Page({
  data: {
    habitId: '',
    habitName: '',
    habitIcon: '',
    startDate: '',
    endDate: '',
    totalDays: 0,
    maxStreak: 0,
    monthDays: 0,
    // 日历相关数据
    year: 0,
    month: 0,
    date: ['日', '一', '二', '三', '四', '五', '六'],
    dateArr: [],
    isToday: 0,
    isTodayWeek: false,
    todayIndex: 0,
    today: 0,
    selectedDate: null,
    habitRecords: {}, // 当前习惯的打卡记录
    userId: '',
    showCancelModal: false,
    cancelDate: null, // 记录要取消的日期
    showPatchModal: false,
    patchDate: null,
    patchLogContent: '',
    patchImage: null,
    showTodayModal: false,
    todayLogContent: '',
    todayImage: null,
    // 添加习惯频次相关数据
    habit_frequency_type: 0, // 1=固定天数，2=每周，3=每月
    habit_frequency_value: 0, // 每周/每月需要打卡的次数
    habit_frequency_days: '', // 固定天数的打卡日期，如"1,2,3"表示周一、二、三
    userScore: 0, // 新增积分字段
    showPatchConfirmModal: false, // 控制补卡确认弹窗
    pendingPatchDate: null, // 临时存储待补卡日期
  },
  onLoad(options) {
    const habit_id = options.habit_id;
    // 优先使用 options.user_id，如果不存在则从本地缓存获取
    const user_id = options.user_id || wx.getStorageSync('userId');
    this.setData({
      habitId: habit_id,
      userId: user_id
    });
    // 初始化日历年月
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let todayDate = now.getDate();
    this.setData({
      year: year,
      month: month,
      today: todayDate,
      isToday: '' + year + month + todayDate,
      selectedDate: todayDate
    });
    // 拉取习惯统计和打卡数据
    this.loadHabitStat(habit_id, user_id);
    this.getHabitRecords(habit_id, user_id);
    this.getMonthDays(user_id, habit_id, year, month);
    this.dateInit();
    // 异步请求用户积分
    wx.request({
      url: 'http://127.0.0.1:3001/getUserScore',
      method: 'GET',
      data: { userId: user_id },
      success: (res) => {
        if (res.data && typeof res.data.score !== 'undefined') {
          this.setData({ userScore: res.data.score });
        } else {
          console.warn('获取用户积分失败或积分数据无效:', res.data);
          this.setData({ userScore: 0 }); // 默认设置为0
        }
      },
      fail: (err) => {
        console.error('请求用户积分接口失败:', err);
        wx.showToast({
          title: '获取积分失败',
          icon: 'none'
        });
        this.setData({ userScore: 0 }); // 默认设置为0
      }
    });
  },
  loadHabitStat(habitId, userId) {
    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabitDetail',
      method: 'GET',
      data: {
        habitId: habitId,
        userId: userId
      },
      success: (res) => {
        if (res.data) {
          const startDate = res.data.habit_createdTime ? res.data.habit_createdTime.split(' ')[0] : '';
          const endDate = res.data.habit_finishedTime ? res.data.habit_finishedTime.split(' ')[0] : '';
          this.setData({
            habitName: res.data.habit_name,
            habitIcon: res.data.habit_img,
            startDate: startDate,
            endDate: endDate,
            totalDays: res.data.habit_num,
            habit_frequency_type: res.data.habit_frequency_type,
            habit_frequency_value: res.data.habit_frequency_value,
            habit_frequency_days: res.data.habit_frequency_days
          });
        } else {
          console.error('getUserHabitDetail failed: res.data is empty or null', res);
        }
      },
      fail: (err) => {
        console.error('getUserHabitDetail request failed:', err);
      }
    });
  },
  getHabitRecords(habitId, userId) {
    wx.request({
      url: 'http://127.0.0.1:3001/getHabitRecords',
      method: 'GET',
      data: {
        habitId: habitId,
        userId: userId
      },
      success: (res) => {
        if (res.data && res.data.records) {
          // 处理为 { '20250601': {log_type: 1}, ... }
          const recordMap = {};
          res.data.records.forEach(r => {
            const y = r.log_year.padStart(4, '0');
            const m = r.log_month.padStart(2, '0');
            const d = r.log_day.padStart(2, '0');
            const key = `${y}${m}${d}`;
            recordMap[key] = r.log_type;
          });
          this.setData({
            habitRecords: recordMap
          }, () => {
            this.dateInit();
          });
        } else {
          console.error('getHabitRecords failed: res.data or res.data.records is empty/null', res);
        }
      },
      fail: (err) => {
        console.error('getHabitRecords request failed:', err);
      }
    });
  },
  getMonthDays(userId, habitId, year, month) {
    wx.request({
      url: 'http://127.0.0.1:3001/getHabitMonthCount',
      method: 'GET',
      data: {
        userId: userId,
        habitId: habitId,
        year: year,
        month: month
      },
      success: (res) => {
        if (res.data && typeof res.data.count !== 'undefined') {
          this.setData({
            monthDays: res.data.count
          });
        } else {
          console.error('getHabitMonthCount failed: res.data or res.data.count is undefined', res);
        }
      },
      fail: (err) => {
        console.error('getHabitMonthCount request failed:', err);
      }
    });
  },
  dateInit: function (setYear, setMonth) {
    let dateArr = [];
    let arrLen = 0;
    let now = setYear ? new Date(setYear, setMonth) : new Date();
    let year = setYear || now.getFullYear();
    let nextYear = 0;
    let month = setMonth || now.getMonth();
    let nextMonth = (month + 1) > 11 ? 1 : (month + 1);
    let startWeek = new Date(year + '/' + (month + 1) + '/1').getDay();
    let dayNums = new Date(year, nextMonth, 0).getDate();
    let obj = {};
    let num = 0;

    // 获取今天的年月日，用于判断未来日期
    const todayDateObj = new Date();

    if (month + 1 > 11) {
      nextYear = year + 1;
      dayNums = new Date(nextYear, nextMonth, 0).getDate();
    }
    arrLen = startWeek + dayNums;
    for (let i = 0; i < arrLen; i++) {
      if (i >= startWeek) {
        num = i - startWeek + 1;
        const logType = this.checkDateHasRecord(year, month + 1, num);

        // 判断是否为未来日期
        const currentDate = new Date(year, month, num); // month here is 0-indexed
        const isFutureDate = currentDate > todayDateObj; // Directly compare Date objects

        obj = {
          isToday: '' + year + (month + 1) + num,
          dateNum: num,
          logType: logType,
          hasRecord: logType === 1,
          patchRecord: logType === 0,
          isFutureDate: isFutureDate // 添加isFutureDate属性
        };
      } else {
        obj = {};
      }
      dateArr[i] = obj;
    }
    this.setData({
      dateArr: dateArr
    });
    let nowDate = new Date();
    let nowYear = nowDate.getFullYear();
    let nowMonth = nowDate.getMonth() + 1;
    let nowWeek = nowDate.getDay();
    let getYear = setYear || nowYear;
    let getMonth = setMonth >= 0 ? (setMonth + 1) : nowMonth;
    if (nowYear == getYear && nowMonth == getMonth) {
      this.setData({
        isTodayWeek: true,
        todayIndex: nowWeek
      });
    } else {
      this.setData({
        isTodayWeek: false,
        todayIndex: -1
      });
    }
  },
  checkDateHasRecord: function (year, month, day) {
    const dateStr = '' + year + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day);
    // 返回 log_type，1=打卡，0=补卡，undefined=无
    return this.data.habitRecords[dateStr];
  },
  lastMonth: function () {
    let year = this.data.month - 2 < 0 ? this.data.year - 1 : this.data.year;
    let month = this.data.month - 2 < 0 ? 11 : this.data.month - 2;
    this.setData({
      year: year,
      month: (month + 1)
    });
    this.dateInit(year, month);
  },
  nextMonth: function () {
    let year = this.data.month > 11 ? this.data.year + 1 : this.data.year;
    let month = this.data.month > 11 ? 0 : this.data.month;
    this.setData({
      year: year,
      month: (month + 1)
    });
    this.dateInit(year, month);
  },
  lookHuoDong: function (e) {
    const dateNum = e.currentTarget.dataset.datenum;
    const clickedYear = e.currentTarget.dataset.year;
    const clickedMonth = e.currentTarget.dataset.month;

    // 获取点击日期的 isFutureDate 状态
    const clickedDateIndex = e.currentTarget.dataset.index;
    const clickedDateData = this.data.dateArr[clickedDateIndex];
    const isFutureDate = clickedDateData && clickedDateData.isFutureDate;

    // 如果是未来日期，则提示不能打卡并返回
    if (isFutureDate) {
      wx.showModal({
        title: '提示',
        content: '不能打卡未来日期',
        showCancel: false,
        confirmText: '知道了'
      });
      return; // 阻止后续操作
    }

    const logType = this.checkDateHasRecord(clickedYear, clickedMonth, dateNum);

    // 获取今天的年月日
    const now = new Date();
    const todayY = now.getFullYear();
    const todayM = now.getMonth() + 1;
    const todayD = now.getDate();

    // 判断是否为今天
    const isToday = (Number(clickedYear) === todayY && Number(clickedMonth) === todayM && Number(dateNum) === todayD);
    // 判断是否为今天之前
    const clickedDate = new Date(clickedYear, clickedMonth - 1, dateNum);
    const todayDate = new Date(todayY, todayM - 1, todayD);

    // 如果已经打卡或补卡，处理取消逻辑
    if (logType === 1 || logType === 0) {
      // 场景：取消非补卡打卡 (logType === 1) 且用户积分小于等于 0
      if (logType === 1 && this.data.userScore <= 0) {
        wx.showModal({
          title: '积分余额不足',
          content: `当前积分余额为${this.data.userScore}，取消打卡后积分将变为${this.data.userScore - 1}，是否确认取消？`,
          confirmText: '确认取消',
          cancelText: '再想想',
          success: (res) => {
            if (res.confirm) {
              // 用户确认取消，直接调用核心取消逻辑
              this._executeCancellation(clickedYear, clickedMonth, dateNum, logType, this.data.habitId, this.data.userId, this.data.userScore);
            }
            // 如果用户选择取消，则不执行任何操作，直接关闭此弹窗
          }
        });
      } else {
        // 其他情况（补卡取消，或正常打卡但积分 > 0），显示自定义的取消确认弹窗
        this.setData({
          showCancelModal: true,
          cancelDate: {
            year: clickedYear,
            month: clickedMonth,
            day: dateNum,
            logType: logType
          }
        });
      }
      return; // 处理完已打卡日期后返回
    }

    // 根据日期类型显示不同的弹窗（针对未打卡日期）
    if (isToday) {
      // 今天未打卡，直接弹出打卡弹窗，不需要消耗积分
      this.setData({
        showTodayModal: true,
        todayLogContent: '',
        todayImage: null
      });
    } else if (clickedDate < todayDate) {
      // 补卡前，先请求后端最新积分
      wx.request({
        url: 'http://127.0.0.1:3001/getUserScore',
        method: 'GET',
        data: { userId: this.data.userId },
        success: (res) => {
          const realScore = res.data && typeof res.data.score !== 'undefined' ? res.data.score : 0;
          if (realScore >= 10) {
            this.setData({
              showPatchConfirmModal: true,
              pendingPatchDate: { year: clickedYear, month: clickedMonth, day: dateNum }
            });
          } else {
            wx.showModal({
              title: '积分余额不足',
              content: `当前积分余额为${realScore}，补卡需要10积分，无法补卡`,
              showCancel: false,
              confirmText: '知道了'
            });
            this.setData({ userScore: realScore }); // 同步本地积分
          }
        }
      });
    } else {
      // 其它情况 (未打卡且非今天也非今天之前的日期，这通常不会发生，或者需要进一步的业务逻辑
      this.setData({
        year: clickedYear,
        month: clickedMonth,
        today: dateNum,
        selectedDate: dateNum
      });
    }
  },
  goBack() {
    wx.navigateBack();
  },
  toToday() {
    // 跳转到今天
  },
  onViewAll() {
    // 这里可以实现跳转或弹窗
    wx.showToast({
      title: '查看所有',
      icon: 'none'
    });
  },
  onLogClick() {
    const { userId, habitId, habitName } = this.data;
    wx.navigateTo({
      url: `/pages/log_list/log_list?user_id=${userId}&habit_id=${habitId}&habit_name=${encodeURIComponent(habitName)}`
    });
  },
  onCancelModal() {
    this.setData({ showCancelModal: false, cancelDate: null });
  },
  onConfirmCancel() {
    const { year, month, day, logType } = this.data.cancelDate;
    const { habitId, userId, userScore } = this.data;

    // 直接关闭自定义模态框
    this.setData({ showCancelModal: false, cancelDate: null });

    // 调用核心取消逻辑
    this._executeCancellation(year, month, day, logType, habitId, userId, userScore);
  },
  onPatchLogInput(e) {
    this.setData({ patchLogContent: e.detail.value });
  },
  onPatchChooseImage() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.setData({ patchImage: res.tempFilePaths[0] });
      }
    });
  },
  onPatchDelImage() {
    this.setData({ patchImage: null });
  },
  onPatchCancel() {
    this.setData({ showPatchModal: false, patchDate: null, patchLogContent: '', patchImage: null });
  },
  onPatchConfirm() {
    const { year, month, day } = this.data.patchDate;
    const { habitId, userId, patchLogContent, patchImage } = this.data;
    const log_type = 0; // 补卡
    const log_year = String(Number(year));
    const log_month = String(Number(month));
    const log_day = String(Number(day));
    // 用当前时间作为 log_CreatedTime
    const now = new Date();
    const localDate = new Date(now.getTime() + 8 * 60 * 60 * 1000);
    const log_CreatedTime = localDate.toISOString().slice(0, 19).replace('T', ' ');
    const doAddLog = (imgUrl = '') => {
      wx.request({
        url: 'http://127.0.0.1:3001/addLog',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          log_content: (patchLogContent || ''),
          habit_id: habitId,
          user_id: userId,
          log_type,
          log_year,
          log_month,
          log_day,
          log_CreatedTime,
          log_img: (imgUrl || '')
        },
        success: (res) => {
          if (res.data.success) {
            // 先获取天数+1再更新
            this.updateHabitNumPlusOne(habitId, userId, () => {
              wx.showToast({ title: '补卡成功', icon: 'success' });
              this.getHabitRecords(habitId, userId);
              this.getMonthDays(userId, habitId, this.data.year, this.data.month);
              this.loadHabitStat(habitId, userId);
              // 同步更新习惯页的完成天数
              const pages = getCurrentPages();
              const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
              if (habitsPage && typeof habitsPage.loadHabits === 'function') {
                habitsPage.loadHabits(userId); // 假设 habitsPage 有 loadHabits 方法
              }
            });
          } else {
            wx.showToast({ title: res.data.message || '补卡失败', icon: 'none' });
          }
          this.setData({ showPatchModal: false, patchDate: null, patchLogContent: '', patchImage: null });
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
          this.setData({ showPatchModal: false, patchDate: null, patchLogContent: '', patchImage: null });
        }
      });
    };
    if (patchImage) {
      wx.uploadFile({
        url: 'http://127.0.0.1:3001/uploadAvatar',
        filePath: patchImage,
        name: 'avatar',
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.success) {
            doAddLog(data.avatarUrl);
          } else {
            wx.showToast({ title: '图片上传失败', icon: 'none' });
          }
        }
      });
    } else {
      doAddLog('');
    }
  },
  onTodayLogInput(e) {
    this.setData({ todayLogContent: e.detail.value });
  },
  onTodayChooseImage() {
    wx.chooseImage({
      count: 1,
      success: (res) => {
        this.setData({ todayImage: res.tempFilePaths[0] });
      }
    });
  },
  onTodayDelImage() {
    this.setData({ todayImage: null });
  },
  onTodayCancel() {
    this.setData({ showTodayModal: false, todayLogContent: '', todayImage: null });
  },
  onTodayConfirm() {
    // 打卡
    const now = new Date();
    const { habitId, userId, todayLogContent, todayImage, year, month, today } = this.data;
    const log_type = 1; // 打卡
    const log_year = String(Number(year));
    const log_month = String(Number(month));
    const log_day = String(Number(today));
    const log_CreatedTime = now.toISOString().slice(0, 19).replace('T', ' ');
    const doAddLog = (imgUrl = '') => {
      wx.request({
        url: 'http://127.0.0.1:3001/addLog',
        method: 'POST',
        header: {
          'Content-Type': 'application/json'
        },
        data: {
          log_content: todayLogContent,
          habit_id: habitId,
          user_id: userId,
          log_type,
          log_year,
          log_month,
          log_day,
          log_CreatedTime,
          log_img: imgUrl
        },
        success: (res) => {
          if (res.data.success) {
            // 先获取天数+1再更新
            this.updateHabitNumPlusOne(habitId, userId, () => {
              // 增加用户积分
              wx.request({
                url: 'http://127.0.0.1:3001/updateUserScore',
                method: 'POST',
                data: { userId: userId, delta: 1 }, // 增加1点积分
                success: (scoreRes) => {
                  if (scoreRes.data.success) {
                    this.setData({ userScore: this.data.userScore + 1 }); // 更新本地积分

                    // 同步更新习惯页的完成天数
                    const pages = getCurrentPages();
                    const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
                    if (habitsPage && typeof habitsPage.loadHabits === 'function') {
                      habitsPage.loadHabits(userId); // 假设 habitsPage 有 loadHabits 方法
                    }

                  } else {
                    console.error('用户积分增加失败:', scoreRes.data.message);
                  }
                },
                fail: (scoreErr) => {
                  console.error('调用增加积分接口失败:', scoreErr);
                }
              });
              wx.showToast({ title: '打卡成功', icon: 'success' });
              this.getHabitRecords(habitId, userId);
              this.getMonthDays(userId, habitId, this.data.year, this.data.month);
              this.loadHabitStat(habitId, userId);
            });
          } else {
            wx.showToast({ title: res.data.message || '打卡失败', icon: 'none' });
          }
          this.setData({ showTodayModal: false, todayLogContent: '', todayImage: null });
        },
        fail: () => {
          wx.showToast({ title: '网络错误', icon: 'none' });
          this.setData({ showTodayModal: false, todayLogContent: '', todayImage: null });
        }
      });
    };
    if (todayImage) {
      wx.uploadFile({
        url: 'http://127.0.0.1:3001/uploadAvatar',
        filePath: todayImage,
        name: 'avatar',
        success: (uploadRes) => {
          const data = JSON.parse(uploadRes.data);
          if (data.success) {
            doAddLog(data.avatarUrl);
          } else {
            wx.showToast({ title: '图片上传失败', icon: 'none' });
          }
        }
      });
    } else {
      doAddLog('');
    }
  },
  updateHabitNumPlusOne: function(habit_id, user_id, cb) {
    wx.request({
      url: 'http://127.0.0.1:3001/getUserHabitDetail',
      method: 'GET',
      data: {
        habitId: habit_id,
        userId: user_id
      },
      success: (res) => {
        let num = 0;
        if (res.data && typeof res.data.habit_num !== 'undefined') {
          num = Number(res.data.habit_num) || 0;
        }
        wx.request({
          url: 'http://127.0.0.1:3001/updateHabitNum',
          method: 'POST',
          data: {
            habit_id,
            user_id,
            habit_num: num + 1,
            isClockedInToday: 1
          },
          success: () => {
            if (cb) cb();
          }
        });
      }
    });
  },
  //补卡确认弹窗的取消和确认
  onPatchConfirmCancel() {
    this.setData({ showPatchConfirmModal: false, pendingPatchDate: null });
  },
  onPatchConfirmOk() {
    // 扣除积分，调用后端接口
    const userId = this.data.userId; // 直接使用 this.data.userId
    wx.request({
      url: 'http://127.0.0.1:3001/updateUserScore',
      method: 'POST',
      data: { userId: userId, delta: -10 },
      success: (res) => {
        if (res.data && res.data.success) {
          // 本地积分同步
          this.setData({
            userScore: this.data.userScore - 10,
            showPatchConfirmModal: false
          });
          // 弹出补卡弹窗
          const date = this.data.pendingPatchDate;
          this.setData({
            showPatchModal: true,
            patchDate: date,
            patchLogContent: '',
            patchImage: null,
            pendingPatchDate: null
          });
        } else {
          wx.showToast({ title: '扣除积分失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
      }
    });
  },
  // 新增辅助函数：执行取消打卡的核心逻辑
  _executeCancellation: function(year, month, day, logType, habitId, userId, userScore) {
    wx.request({
      url: 'http://127.0.0.1:3001/deleteLog',
      method: 'POST',
      data: {
        habit_id: habitId,
        user_id: userId,
        log_year: year,
        log_month: month,
        log_day: day
      },
      success: (res) => {
        if (res.data.success) {
          // 先获取当前天数，然后减1
          wx.request({
            url: 'http://127.0.0.1:3001/getUserHabitDetail',
            method: 'GET',
            data: {
              habitId: habitId,
              userId: userId
            },
            success: (habitRes) => {
              if (habitRes.data && typeof habitRes.data.habit_num !== 'undefined') {
                const currentNum = Number(habitRes.data.habit_num) || 0;
                // 更新习惯天数
                wx.request({
                  url: 'http://127.0.0.1:3001/updateHabitNum',
                  method: 'POST',
                  data: {
                    habit_id: habitId,
                    user_id: userId,
                    habit_num: currentNum - 1,
                    isClockedInToday: 0
                  },
                  success: (updateRes) => {
                    if (updateRes.data.success) {
                      wx.showToast({ title: '已取消打卡', icon: 'success' });
                      // 刷新数据
                      this.getHabitRecords(habitId, userId);
                      this.getMonthDays(userId, habitId, this.data.year, this.data.month);
                      this.loadHabitStat(habitId, userId);

                      // 扣除用户积分
                    
                      if (logType !== 0) { // 如果是补卡，则不扣除积分
                        wx.request({
                          url: 'http://127.0.0.1:3001/updateUserScore',
                          method: 'POST',
                          data: { userId: userId, delta: -1 },
                          success: (scoreRes) => {
                            if (scoreRes.data.success) {
                              this.setData({ userScore: userScore - 1 });

                              // 同步更新习惯页的完成天数
                              const pages = getCurrentPages();
                              const habitsPage = pages.find(page => page.route === 'pages/habits/habits');
                              if (habitsPage && typeof habitsPage.loadHabits === 'function') {
                                habitsPage.loadHabits(userId); // 假设 habitsPage 有 loadHabits 方法
                              }

                            } else {
                              console.error('用户积分扣除失败:', scoreRes.data.message);
                            }
                          },
                          fail: (scoreErr) => {
                            console.error('调用扣除积分接口失败:', scoreErr);
                          }
                        });
                      }
                    } else {
                      wx.showToast({ title: '更新天数失败', icon: 'none' });
                    }
                  },
                  fail: () => {
                    wx.showToast({ title: '更新天数失败', icon: 'none' });
                  }
                });
              } else {
                wx.showToast({ title: '获取习惯信息失败', icon: 'none' });
              }
            },
            fail: () => {
              wx.showToast({ title: '获取习惯信息失败', icon: 'none' });
            }
          });
        } else {
          wx.showToast({ title: res.data.message || '取消失败', icon: 'none' });
        }
        // 不需要在这里设置 showCancelModal: false，因为它是由 lookHuoDong 或 onConfirmCancel 的调用者处理的
      },
      fail: () => {
        wx.showToast({ title: '网络错误', icon: 'none' });
        // 同样不需要在这里设置 showCancelModal: false
      }
    });
  },
}); 